<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Session;
use think\Request;
use think\Cache;
use think\Db;
use addons\epay\library\Service;

/**
 * 公共方法(不需要登录)
 */
class Pub extends Frontend {

    public function _initialize() {
//        session('user_id', 1);
        $this->iUserId = Session('user_id');
//        parent::_initialize();
        $info = db('configure')->where('key', 'fenxiang')->find();
        $info = json_decode($info['desc'], true);

        $user_box_id = Session('user_box_id');
        $box_no = db('user_box')->where('user_box_id', $user_box_id)->value('box_no');
        $share_url = 'https://www.mohebianli.com/index/pub/index/box/' . base64_encode($box_no);
        $this->assign('user_box_id', $this->userBoxId);
        $this->assign('share_url', $share_url);
        $this->assign('data', $info);
    }

    public function index() {

        $box = input('box');

        $box = base64_decode($box);
        $box_info = db('user_box')->where(['box_no' => $box, 'status' => 1])->find();

        if ($box_info) {
            Session('user_box_id', $box_info['user_box_id']);
            $this->userBoxId = $box_info['user_box_id'];
            $this->redirect('https://www.mohebianli.com' . url('Index/index'));
        } else {
            return $this->view->fetch();
        }
    }

    public function unFollow() {
        return $this->view->fetch();
    }

    public function userStatus() {
        $user_info = db('users')->where(['user_id' => $this->iUserId])->find();
        $this->assign('user_info', $user_info);
        return $this->view->fetch();
    }

    public function bindPhone() {
        $is_shiming = db('configure')->where(['key' => 'shimingrenzhen'])->value('desc');

        $to_url = Session('to_url') ? Session('to_url') : url('Index/index');

        if ($this->request->isPost()) {
            $phone = $this->request->param('phone');
            $vcode = $this->request->param('vcode');

            if (empty($phone)) {
                $this->error('请填写手机号');
            }

            if (Cache::get($phone) != $vcode) {
                $this->error('验证码错误');
            }

            //删除缓存
            Cache::rm($phone);

            $data['phone'] = $phone;
            $res = db('users')->where(['user_id' => $this->iUserId])->update($data);

            if ($is_shiming == 1) {
                $coupon_id = db('configure')->where('key', 'bangdingshoujihaoyouhuiquan')->value('desc');
                //绑定手机号优惠券
                if ($coupon_id) {
                    receiveCoupon($this->iUserId, $coupon_id);
                }
                $this->success('进入下一步', ['url' => url('Pub/userAuth')]);
            } else {
                //领取新人优惠券
                $coupon_id = db('configure')->where(['key' => 'xinrenyouhuiquan'])->value('desc');
                if ($coupon_id) {
                    receiveCoupon($this->iUserId, $coupon_id);
                }
                //绑定手机号优惠券
                $coupon_id = db('configure')->where('key', 'bangdingshoujihaoyouhuiquan')->value('desc');
                if ($coupon_id) {
                    receiveCoupon($this->iUserId, $coupon_id);
                }
                $this->success('领取成功', ['url' => $to_url]);
            }
        } else {
            $user_info = db('users')->where(['user_id' => $this->iUserId])->find();

            if ($user_info['phone']) {
                $this->redirect($to_url);
            }

            if ($user_info) {
                if (strpos($user_info['avatar'], 'http') === false) {
                    $user_info['avatar'] = 'http://mohebianli.oss-cn-zhangjiakou.aliyuncs.com' . $user_info['avatar'];
                }
            }
            $this->assign('is_shiming', $is_shiming);
            $this->assign('user_info', $user_info);
            return $this->view->fetch();
        }
    }

    //微信授权
    public function auth() {
        $code = $_GET['code'];
        $state = $_GET['state'];
//        echo 123;die;
        //换成自己的接口信息
        $appid = 'wxc9abd79c9ddd15e3';
        $appsecret = 'ad30813b82c81ebe139aff154b7bb85c';
        if (empty($code)) {
            $this->ajaxError('授权失败');
        }


        //拿code
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $token = json_decode(file_get_contents($token_url));
        if (isset($token->errcode)) {
            echo '<h1>错误：</h1>' . $token->errcode;
            echo '<br/><h2>错误信息：</h2>' . $token->errmsg;
            exit;
        }
        //拿access_token
        $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . $token->refresh_token;
        $access_token = json_decode(file_get_contents($access_token_url));
        if (isset($access_token->errcode)) {
            echo '<h1>错误：</h1>' . $access_token->errcode;
            echo '<br/><h2>错误信息：</h2>' . $access_token->errmsg;
            exit;
        }


        /* ------------------------------不需要判断用户是否关注拿的用户信息----------------- */
//        https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
//        $user_info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token->access_token . '&openid=' . $access_token->openid . '&lang=zh_CN';
//        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token->access_token . '&openid=' . $access_token->openid . '&lang=zh_CN';
//        //转成对象
//        $user_info = json_decode(file_get_contents($user_info_url));
//        if (isset($user_info->errcode)) {
//            echo '<h1>错误：</h1>' . $user_info->errcode;
//            echo '<br/><h2>错误信息：</h2>' . $user_info->errmsg;
//            exit;
//        }

        /* ---------------------------不需要关注拿的用户信息end----------------- */



        /* ------------------------------需要判断用户是否关注拿的用户信息----------------- */
        $token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        $token = json_decode(file_get_contents($token_url));
        if (isset($token->errcode)) {
            echo '<h1>错误：</h1>' . $token->errcode;
            echo '<br/><h2>错误信息：</h2>' . $token->errmsg;
            exit;
        }

        //需要关注的用户信息
        $user_info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $token->access_token . '&openid=' . $access_token->openid . '&lang=zh_CN';
        $user_info = json_decode(file_get_contents($user_info_url));
        if (isset($user_info->errcode)) {
            echo '<h1>错误：</h1>' . $user_info->errcode;
            echo '<br/><h2>错误信息：</h2>' . $user_info->errmsg;
            exit;
        }

        /* ---------------------------需要关注拿的用户信息end----------------- */

        $rs = json_decode(json_encode($user_info), true); //返回的json数组转换成array数组
        $openid = $rs['openid'];

        //判断是否关注公众号
        if ($rs['subscribe'] == 0) {
            //未关注公众号
            header('Location:' . 'https://www.mohebianli.com' . url('unFollow'));
        } else {

            //自己的业务逻辑

            $users = db('users')->where(array('wx_openid' => $openid))->find();
//
//            if (empty($users['phone'])) {
//                header('Location:' . 'http://www.mohebianli.com' . url('My/bindphone'));
//            }

            if (!empty($users)) {
                session('user_id', $users['user_id']);

                header('Location:' . 'https://www.mohebianli.com' . url('Index/index'));
            } else {
                $arrData = array(
                    'nick_name' => $rs['nickname'],
                    'avatar' => $rs['headimgurl'],
                    'wx_openid' => $rs['openid'],
//                    'refusal_reason' => json_encode($rs)
                );

                $is_shiming = db('configure')->where(['key' => 'shimingrenzhen'])->value('desc');

                //是否需要实名认证
                if ($is_shiming == 0) {
                    $arrData['user_status'] = 1;
                }

                $user_id = db('users')->insertGetId($arrData);
                if ($user_id) {
                    //TODO 绑定手机号

                    session('user_id', $user_id);
                    $wallet['user_id'] = $user_id;
                    db('wallet')->insert($wallet);
                    header('Location:' . 'https://www.mohebianli.com' . url('bindphone'));
                } else {
                    echo '<h1>错误：</h1>';
                    echo '<br/><h2>错误信息：请联系平台人员。</h2>';
                    exit;
                }
                //$this->display('Public/register');
            }
        }
    }

    /**
     * 验证码发送
     */
    public function sendVcode() {
        $phone = $this->request->param('phone');
        if (!is_numeric($phone)) {
            $this->error('非法手机号');
        }
        $res = createVerify($phone);
        $this->success('发送成功', $res);
    }

    public function userAuth() {
        if ($this->request->isPost()) {
            $real_name = $this->request->param('real_name');
            $identity_number = $this->request->param('identity_number');

            $identity_img_list[] = $this->request->param('identity_img_list0');
            $identity_img_list[] = $this->request->param('identity_img_list1');
            $identity_img_list[] = $this->request->param('identity_img_list2');

            $data['identity_number'] = $identity_number;
            $data['real_name'] = $real_name;

            $data['user_status'] = 0;
            $data['createtime'] = date('Y-m-d', time());

            $data['identity_img_list'] = implode(',', $identity_img_list);

            $res = db('users')->where(array('user_id' => $this->iUserId))->update($data);

            $this->redirect('userStatus');
        } else {
            $user_info = db('users')->where(['user_id' => $this->iUserId])->find();

            if ($user_info) {
                $user_info['identity_img_list'] = explode(',', $user_info['identity_img_list']);
            }
            $this->assign('user_info', $user_info);
            return $this->view->fetch();
        }
    }

    public function disable() {

        $tel = db('configure')->where(['key' => 'kefudianhua'])->value('desc');
        $this->assign('tel', $tel);
        return $this->view->fetch();
    }

    public function getXq() {
        $city = $this->request->param('city');

        $arr = explode(',', $city);
        $name = $arr[count($arr) - 1];

        $id = db('area')->where('name', $name)->value('id');

        $list = db('house')->field('house_id as value,house_name as text')->where('area', $id)->where('house_type', 0)->order('createtime', 'desc')->select();

        if ($list) {
            $this->success('', $list);
        } else {
            $this->error();
        }
    }

    public function getHouse() {
        $id = $this->request->param('id');

        $list = db('house')->field('house_id as value,house_name as text')->where('pid', $id)->where('is_del', 0)->order('createtime', 'desc')->select();

        if ($list) {
            $this->success('', $list);
        } else {
            $this->error();
        }
    }

    public function clearSession() {
        Session::clear();
    }

}
